package actions;

import java.sql.SQLException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.RowSet;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import db.DbException;
import forms.StudentForm;
import model.UserModel;

public class UserAction extends Action {
	
	private static final boolean DEBUG = true;
	private static final int UNKNOWN = 0;
	
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws DbException {
		
		String path = mapping.getPath();
		
		if (DEBUG) {
			System.err.println("UserAction: " + path);
		}
		
		if (path.equals("/index")) {
			
			String user = request.getUserPrincipal().getName();
			
			if (DEBUG) {
				System.err.println("UserAction: user(" + user + ")");
			}
			
			if (user != null) {
				RowSet rset = UserModel.getUserRole(user);
				String role = "";
				
				try {
					while (rset.next()) {
						role = rset.getString("role");
					}
				} catch (SQLException ex) {
					System.err.println("SQLException: " + ex.getMessage());
				}
				
				if (DEBUG) {
					System.err.println("UserAction: role(" + role + ")");
				}
				
				if (role.equals("admin")) {
					return mapping.findForward("admin");
				}
				else if (role.equals("student")){
					return mapping.findForward("student");
				}
				else if (role.equals("reviewer")) {
					return mapping.findForward("reviewer");
				}
			}
		}
		else if (path.equals("/myApplication")) {
			String user = request.getUserPrincipal().getName();
			
			if (DEBUG) {
				if(user!= null)
					System.err.println("UserAction: user(" + user + ")");
			}
			
			if (user != null) {
				RowSet users = UserModel.getUser(user);
				int app_id = 0;
				
				try {
					while(users.next()) {
						app_id = users.getInt("student_id");
					}
				} catch (SQLException e) {
					System.err.println("SQLException: " + e.getMessage());
				}
				
				if (DEBUG) {
					System.err.println("UserAction: app_id(" + app_id + ")");
				}
				
				if (app_id > UNKNOWN) {
					
					if (DEBUG) {
						System.err.println("UserAction: continuing application process");
					}
					
					request.getSession().setAttribute("studentapp_id", app_id);
					
					return mapping.findForward("done");
				}
			}
			
			if (DEBUG) {
				System.err.println("UserAction: starting application process");
			}
			
			return mapping.findForward("start");
		}
		
		if (DEBUG) {
			System.err.println("UserAction: returning to index");
		}
		
		return mapping.findForward("default");
	}
}
